#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
Attributes:
    __version__ (str): "0.0.1"
    __copyright__ (str): "Copyright (C) 2025 z"
    __license__ (str): "MIT"
    __author__ (str): "Z"
"""

import json, requests, datetime

from wingman import logger
from wingman.common.error import ErrorCode
from config.system import FEISHU_APP_ID, FEISHU_APP_SECRET


class FeiShuTalk:
    """飞书发消息,app_access_token/tenant_access_token 和 user_access_token不同所以弄了两个类"""

    def app_access_token(self):
        """获取tenant_access_token"""
        url = "https://open.feishu.cn/open-apis/auth/v3/app_access_token/internal/"
        data = {"app_id": f"{FEISHU_APP_ID}", "app_secret": f"{FEISHU_APP_SECRET}"}
        response = requests.post(url, data)
        self.app_access_token = response.json()["app_access_token"]
        return response.json()["app_access_token"]

    def get_send(self, access, title, message):
        url = f"https://open.feishu.cn/open-apis/bot/v2/hook/{access}"
        header = {"Content-Type": "application/json; charset=utf-8", "Authorization": f"Bearer {self.app_access_token}"}

        if isinstance(message, dict):
            message_str = ""
            for key, value in message.items(): 
                if key != "num_hits" or key != "num_matches":
                    message_str = message_str + "- " + str(key).replace("#", "") + ":" + str(value).replace("#", "") + "\n"
        else:
            message_str = message

        data_json = json.dumps({
            "msg_type": "post",
            "content": {"post": {"zh_cn": {"title": f"{title}", "content": [[
                    {"tag": "text", "text": f"{message_str}"+ str(datetime.datetime.now()) + "\n"},
                    # {"tag": "at","user_id": "9cbe1b4f"}  #用户ID
                    ]]}}},
            })
        # 单聊
        # user_data = json.dumps({
        #    "message_id": "om_402848e3343ef98c89c4ebc1c2077a6d"
        # })
        # 向群里发送消息
        # chat_data={"chat_id":chat_id,
        #     "msg_type":"text",
        #     "content":{
        #         "text":"%s<at user_id=\"%s\">test</at>"%(message_str,user_id)
        #     }
        # }
        # chat_data={"chat_id":chat_id, "msg_type":"post",
        #     "content":{ "post": {"zh_cn": {"title": title, "content": 
        #             [[
        #             {"tag": "text", "text": "message_str" }, 
        #             {"tag": "at","user_id": user_id}
        #             ]] } } },
        # }
        # # 给个人发送消息
        # user_data={"user_id":user_id,
        #     "msg_type":"text",
        #     "content":{
        #         "text":"%s<at user_id=\"%s\">test</at>"%(message_str,user_id)
        #     }
        # }
        try:
            request = requests.post(url, data=data_json, headers=header)
            result = request.json()
            # logger.info(ErrorCode.SUCCESS.value, result, __name__)
        except requests.exceptions.RequestException as e:
            result = str(e)
            logger.error(ErrorCode.FEISHU_REQUESTS.value, result, __name__)
        except Exception:
            logger.error(ErrorCode.FEISHU_REQUESTS.value, result, __name__)
        finally:
            return result


if __name__ == '__main__':
    fs = FeiShuTalk()
    print(fs.app_access_token())
    print(fs.get_send("11d3da3a-eccb-43da-97a0-beaa049cf10c", "title", "_text-:"))
